<template>
	<view class="container">
		<view class="search_top">
			<u-search
				class="search"
				v-model="searchContent"
				:clearabled="true"
				:height="30"
				shape="square"
				bgColor="white"
				:animation="true"
				@custom="search()"
				@clear="clearSearchContent()"
			></u-search>
		</view>
		<h3 class="tab-header">
		    <text
				class="tab-item"
				:class="{'inactive': !isShowPost}"
				@click="showPost()"
			>博客</text>
		    <text
				class="tab-item"
				:class="{'inactive': isShowPost}"
				@click="showUser()"
			>用户</text>
		</h3>
		<scroll-view
			scroll-y="true"
			v-if="isShowPost"
			class="show_post"
			@scrolltolower="loadMore()">
			<view
				v-for="(searchPostResult, index) in searchPostResults"
				:key="index"
				@click="gotoPost(searchPostResult)"
				class="post-item">
				<view class="post-details">
					<h3 class="post-title" v-html="searchPostResult.title"></h3>
					<view style="display: flex; width: 100%;">
						<view style=" width: 450rpx;">
							<view class="author-info">
								<u-avatar :src="searchPostResult.userAvatar" mode="aspectFill" shape="circle" class="avatar" size="30"></u-avatar>
								<text class="author-name">{{searchPostResult.authorName}}</text>
							</view>
							<view style="margin-left: 18rpx;color: #888;">
								<text>{{searchPostResult.content}}</text>
							</view>
						</view>
						<u-image :src="searchPostResult.cover" width="250rpx" mode="aspectFill" height="150rpx" style="margin-left: auto; justify-content: center"></u-image>
					</view>
					
					<view class="post-meta">
						<text>{{searchPostResult.commentsCount}}评论 {{searchPostResult.likesCount}}点赞</text>
						<text class="create-time">{{searchPostResult.createTime}}</text>
					</view>
				</view>
			</view>
			<view v-if="loading" class="loading">
				<text class="loading-text">Loading...</text>
			</view>
			<view v-if="(searchPostResults.length>0)&&!postHasmore" class="loading">
				<text class="loading-text">No more search result!</text>
			</view>
			<view style="padding-top: 100rpx;text-align: center;" v-if="(searchPostResults.length<=0)&&!postHasmore&&!loading">
				<!-- <u-image mode="aspectFit" src="/static/gif/refresh_yu_4.gif" style="margin-left: 50rpx;"></u-image> -->
				<text class="loading-text" >抱歉，没有找到任何相关博客</text>
			</view>
		</scroll-view>
		<scroll-view v-if="!isShowPost" class="show_user" scroll-y="true" @scrolltolower="loadMore()">
			<view
				v-for="(searchUserResult, index) in searchUserResults"
				:key="index"
				class="user-item"
				@click="gotoUserInfo(searchUserResult)"
			>
				<u-avatar :src="searchUserResult.userAvatar" mode="aspectFill" shape="circle" class="user-avatar" size="50"></u-avatar>
				<text class="user-name">{{searchUserResult.username}}</text>
			</view>
			<view v-if="loading" class="loading">
				<text class="loading-text">Loading...</text>
			</view>
			<view v-if="(searchUserResults.length>0)&&!userHasmore" class="loading">
				<text class="loading-text">No more search result!</text>
			</view>
			<view style="padding-top: 100rpx;text-align: center;" v-if="(searchUserResults.length<=0)&&!userHasmore&&!loading">
				<!-- <u-image mode="aspectFit" src="/static/gif/refresh_yu_4.gif" style="margin-left: 50rpx;"></u-image> -->
				<text class="loading-text" >抱歉，没有找到任何相关用户</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import request from "../../utils/request.js";
	import file from "../../utils/file.js";
	
export default {
	data() {
		return {
			searchContent: '',
			isShowPost: true,
			searchPostResults: [],
			searchUserResults: [],
			loading: false,
			postHasmore: true,
			userHasmore:true,
			postCurrentPage: 0,
			userCurrentPage: 0,
			pageSize: 10,
			uid: '',
			token: '',
		}
	},
	methods: {
		initPage(searchContent) {
			this.uid = uni.getStorageSync('UID');
			this.token = uni.getStorageSync('token');
			if (this.uid && this.token) {
				this.searchContent = searchContent;
				this.search();
			} else {
				uni.redirectTo({
					url: '/pages/login/login'
				});
			}
		},
		search() {
			console.log(this.searchContent);
			if (this.searchContent == '') {
				return;
			}
			const searchHistorys=uni.getStorageSync("searchHistorys");
			const index=searchHistorys.indexOf(this.searchContent);
			if(index>=0){
				searchHistorys.splice(index,1);
			}
			searchHistorys.unshift(this.searchContent);
			uni.setStorageSync("searchHistorys",searchHistorys);
			// 清空旧的搜索结果
			this.searchPostResults = [];
			this.searchUserResults = [];
			this.postCurrentPage = 0;
			this.userCurrentPage = 0;
			this.hasmore = true;

			if (this.isShowPost) {
				this.searchPost();
			} else {
				this.searchUser();
			}
		},
		searchPost() {
		    this.loading = true; // 开始加载
		    uni.request({
		        url: this.baseUrl + '/searchPost',
		        method: 'POST',
		        data: {
		            data: {
		                searchContent: this.searchContent,
		                currentPage: this.postCurrentPage,
		                pageSize: this.pageSize
		            },
		            msgType: 'searchPost'
		        },
		        header: {
		            'Content-Type': 'application/json',
		            'token': this.token,
		            'uid': this.uid
		        },
		        success: (res) => {
		            const array = res.data.data;
		            console.log("fdsfsdf",res.data.data)
		            if (array.length > 0) {
		                for (let i = 0; i < array.length; i++) {
		                    const s = {
		                        postId: array[i].postId,
		                        userId: array[i].userId,
		                        authorName: '',
		                        userAvatar: '',
								cover:'',
		                        title:this.highlightKeyword(array[i].title, this.searchContent),
		                        content:array[i].content,
		                        likesCount: this.formatNumber(array[i].likesCount),
		                        commentsCount: this.formatNumber(array[i].commentsCount),
		                        createTime: array[i].createdAt.split('T')[0]
		                    };
							//console.log(s.title);
		                    this.searchPostResults.push(s);
		                }
		                this.postCurrentPage += 1;
		                if (array.length < this.pageSize) {
		                    this.postHasmore = false; // 如果返回的数量小于页面大小，表示没有更多数据
		                }
		                this.getSearchUsername(this.searchPostResults);
		                this.getSearchAvatar(this.searchPostResults);
						this.getSearchResultCover(this.searchPostResults);
		            } else {
		                this.postHasmore = false;
		            }
		        }
		    });
			this.loading = false; // 结束加载
		},

		searchUser() {
			// 用户搜索的逻辑
			this.loading=false;
			uni.request({
				url: this.baseUrl + '/searchUser',
				method: 'POST',
				data: {
					data: {
						searchContent: this.searchContent,
						currentPage: this.userCurrentPage,
						pageSize: this.pageSize
					},
					msgType: 'searchUser'
				},
				header: {
					'Content-Type': 'application/json',
					'token': this.token,
					'uid': this.uid
				},
				success: (res) => {
					const array = res.data.data;
					//console.log(array);
					if (array.length > 0) {
						for(let i=0;i<array.length;i++){
							const s={userId:array[i].userId,username:array[i].username,userAvatar:''};
							this.searchUserResults.push(s);
						}
						this.userCurrentPage = this.userCurrentPage+1;
						//console.log(array.length);
					}
					if (array.length < this.pageSize) {
						this.userHasmore = false; // 没有更多用户
					}
					this.getSearchAvatar(this.searchUserResults);
				}
			});
			this.loading=false;
		},
		async getSearchUsername(list) {
			const requests = list.filter(item=>item.userId !== ''&&item.authorName=='').map(item => {
				return uni.request({
					url: this.baseUrl + '/getUsername',
					method: 'POST',
					data: {
						data: {
							userId: item.userId
						},
						msgType: 'getUsername'
					},
					header: {
						'Content-Type': 'application/json',
						'token': this.token,
						'uid': this.uid
					}
				}).then(res => {
					item.authorName = res.data.data.username;
				});
			});
			await Promise.all(requests).catch(err => console.error(err));
		},
		async getSearchAvatar(list) {
		    const requests = list
		        .filter(item => item.userId !== '' && item.userAvatar === '') // 过滤无效请求
		        .map(async item => {
		            try {
		                const res = await uni.request({
		                    url: this.baseUrl + '/getUserAvatar',
		                    method: 'POST',
		                    data: {
		                        data: {
		                            userId: item.userId
		                        },
		                        msgType: 'getUserAvatar'
		                    },
		                    header: {
		                        'Content-Type': 'application/json',
		                        'token': this.token,
		                        'uid': this.uid
		                    }
		                });

		                //console.log(item.userId);

		                if (res.data.code === 1) {
		                    const userAvatar = res.data.data.imgType + 'base64,' + res.data.data.userAvatar;
		                    item.userAvatar = userAvatar;
		                } else {
		                    //console.error(`Failed to get avatar for userId: ${item.userId}, code: ${res.data.code}`);
		                }
		            } catch (err) {
		                console.error(`Error fetching avatar for userId: ${item.userId}`, err);
		            }
		        });

		    // 等待所有请求完成
		    await Promise.all(requests);
		},
		async getSearchResultCover(list) {
		    // 筛选出有效请求
		    const requests = list
		        .filter(item => item.postId !== '' && item.cover === '') // 过滤无效请求
		        .map(async item => {
		            
		            console.log('Fetching cover for postId: ' + item.postId);
		            const url = `${this.baseUrl}/file/${item.postId}?type=cover`;
		            const result = await request.sendUniGetRequestByNetWork(item.postId, undefined, url);
		               
					console.log(result);
		            // 正确的 Base64 拼接格式
		            item.cover = `data:image/${result.data.imgType};base64,${result.data.fileContent}`;
		            //console.log('Cover updated:', item.cover);    
		            
		        });
		
		    // 等待所有请求完成
		    await Promise.all(requests);
		},


		showPost() {
			if(this.isShowPost){
				return;
			}
			this.isShowPost = true;
			this.search();

		},
		showUser() {
			if(!this.isShowPost){
				return;
			}
			this.isShowPost = false;
			this.search();
		},
		loadMore() {
			if(this.searchContent==''){
				return;
			}
			if (this.isShowPost&&this.postHasmore) {
				this.searchPost(); // 加载更多帖子
			}
			if(!this.isShowPost&&this.userHasmore){
				this.searchUser(); // 加载更多用户
			}
		},
		gotoUserInfo(searchUserResult){
			uni.navigateTo({
				url:'/pages/personalInformation/personalInformation?uid='+searchUserResult.userId+'&&username='+searchUserResult.username
			})
		},
		gotoPost(searchPostResult){
			uni.navigateTo({
				url:'/pages/blogArticleDisplay/blogArticleDisplay?id='+searchPostResult.postId
			});
		},
		formatNumber(num) {
		    if (num >= 100000000) { // 大于等于1亿
		        return (num / 100000000).toFixed(1) + '亿'; // 转换为亿
		    } else if (num >= 10000) { // 大于等于1万
		        return (num / 10000).toFixed(1) + 'w'; // 转换为万
		    }
		    return num.toString(); // 小于1万的数字直接返回
		},
		highlightKeyword(text, keyword) {
		    if (!keyword) return text; // 如果没有关键字，直接返回原文本
		    const regex = new RegExp(`(${keyword})`, 'gi'); // 创建一个正则表达式，不区分大小写
		    return text.replace(regex, '<span style=" color: red;">\$1</span>'); // 用 span 标签包裹匹配的关键字
		},
		clearSearchContent(){
			this.searchContent='';
			uni.navigateBack({
				url:'/pages/search/search'
			})
		},
	},
	onLoad(param) {
		let searchContent = param.searchContent;
		searchContent = decodeURIComponent(searchContent);
		this.initPage(searchContent);
	},
	mounted() {
		//this.initPage(this.searchContent);
	},


}
</script>


<style>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh; /* 占满整个视窗高度 */
}

.search_top {
	width: 100%;
	background: linear-gradient(to right, #9fe1fa, #f4edc9);
	padding: 10rpx 0;
}

.search {
	padding: 10rpx 20rpx;
}

.tab-header {
	background: linear-gradient(to right, #9fe1fa, #f4edc9);
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.tab-item {
	flex: 1;
	text-align: center;
	color: #333;
	font-weight: bold;
	padding: 10rpx;
	transition: background-color 1s ease;
}

.tab-item.inactive {
	background: white;
}

.show_post {
	flex: 1; /* 占据剩余的高度 */
	overflow-y: auto; /* 允许垂直滚动 */
}

.post-item {
	display: flex; /* 使用 Flexbox 布局 */
	align-items: flex-start; /* 垂直对齐 */
	margin-bottom: 15rpx; /* 每个帖子之间的间距 */
	margin: 10rpx;
	padding: 10rpx;
	background-color: #ffffff; /* 帖子背景颜色 */
	border-radius: 5px; /* 圆角 */
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

.avatar {
	display: inline-flex;
	margin-right: 10rpx; /* 头像右边距 */
}

.author-info {
	display: flex; /* 使用 Flexbox 布局 */
	align-items: center; /* 垂直居中对齐 */
	max-width: 400rpx;
}

.post-details {
	flex: 1; /* 占据剩余空间 */
}

.post-title {
	font-size: 16px; /* 帖子标题字体大小 */
	color: #333; /* 帖子标题颜色 */
	margin: 0; /* 去掉默认边距 */
	overflow: hidden; /* 隐藏溢出部分 */
	text-overflow: ellipsis; /* 省略号 */
	max-width: 600rpx; /* 限制最大宽度 */
}

.post-meta {
	display: flex; /* 使用 Flexbox 布局 */
	justify-content: space-between; /* 使作者和时间分开 */
	margin-top: 5rpx; /* 上边距 */
	font-size: 25rpx;
	color: #888; /* 元数据颜色 */
}

.author-name {
	margin-left: 5rpx; /* 给作者名字一些左边距 */
}

.create-time {
	margin-left: 10rpx; /* 给创建时间一些左边距 */
}

.show_user {
	flex: 1; /* 占据剩余的高度 */
	overflow-y: auto; /* 允许垂直滚动 */
}

.user-item {
	display: flex; /* 使用 Flexbox 布局 */
	align-items: center; /* 垂直居中对齐 */
	margin: 10rpx;
	padding: 10rpx;
	background-color: #ffffff; /* 用户背景颜色 */
	border-radius: 5px; /* 圆角 */
	margin-bottom: 10rpx; /* 用户项之间的间距 */
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

.user-avatar {
	margin-right: 20rpx; /* 用户头像右边距 */
}

.user-name {
	color: #333; /* 用户名颜色 */
}

.loading {
	text-align: center;
	padding: 20rpx;
}

.loading-text {
	color: gainsboro;
	font-size: 20px; /* 加载文本字体大小 */
}

</style>
